package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
     @Autowired
     private UserMapper userMapper;
     @Autowired
     private WeChatProperties weChatProperties;
     public final static String url ="https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 客户端登录
     *
     * @param dto
     * @return
     */
    @Override
    public Result<UserLoginVO> loginUser(UserLoginDTO dto) {
        //进行非空判断
        if(dto.getCode()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //1.调用微信登录凭证校验接口
        //1.2 封装请求参数
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",dto.getCode());
        map.put("grant_type","authorization_code");
        //发起请求
        String body = HttpClientUtil.doGet(url,map);
        //把请求中的数据转换成map
        Map map1 = JSONObject.parseObject(body, Map.class);
        //进行判断map1是否有值
        if(map1==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //解析body字符串，然后获取openId
        String openid = (String) map1.get("openid");
        //查询数据库是否有数据
        User byId = userMapper.getById(openid);
        //判断是否有数据
        if(byId==null){
                byId=User.builder()
                        .openid(openid)
                        .createTime(LocalDateTime.now())
                        .build();
                userMapper.add(byId);
        }
        //进行封装
        UserLoginVO vo=UserLoginVO.builder()
                .id(byId.getId())
                .openid(openid)
                .token(JwtUtil.getToken(byId.getId()))
                .build();
        //返回封装的vo
        return Result.success(vo);
    }
}
